package nz.co.doherty.gwtpbreadcrumbs.client.ui.topbar;

import java.util.ArrayList;
import java.util.Stack;

import com.google.inject.Inject;
import com.philbeaudoin.gwtp.mvp.client.EventBus;
import com.philbeaudoin.gwtp.mvp.client.PresenterWidgetImpl;
import com.philbeaudoin.gwtp.mvp.client.proxy.PlaceManager;
import com.philbeaudoin.gwtp.mvp.client.proxy.SetPlaceTitleHandler;
import com.philbeaudoin.gwtp.mvp.client.proxy.TokenFormatException;

public class TopBarPresenter extends PresenterWidgetImpl<TopBarView> {

	public class Breadcrumb {
		private String token;
		private String title;
		private int level;

		public Breadcrumb(String token) {
			this.token = token;
		}

		public Breadcrumb(int level) {
			this.level = level;
			this.token = placeManager.buildRelativeHistoryToken(level + 1);
		}

		public void init() {
			TopBarPresenter.this.placeManager.getCurrentTitle(this.level,
				new SetPlaceTitleHandler() {

					@Override
					public void onSetPlaceTitle(String title) {
						Breadcrumb.this.title = title;
						TopBarPresenter.this.titlesRemaining--;
						TopBarPresenter.this.updateBreadcrumbs();
					}
				});

		}

		public String getToken() {
			return this.token;
		}

		public String getTitle() {
			return this.title;
		}
	}

	private int titlesRemaining;
	private final PlaceManager placeManager;
	private ArrayList<Breadcrumb> breadcrumbs;

	@Inject
	public TopBarPresenter(final EventBus eventBus,
			final PlaceManager placeManager, final TopBarView view) {
		super(eventBus, view);

		this.placeManager = placeManager;
		this.breadcrumbs = new ArrayList<Breadcrumb>();
	}

	@Override
	protected void onBind() {
		super.onBind();
	}

	@Override
	protected void onReveal() {
		super.onReveal();
	}

	@Override
	protected void onReset() {
		super.onReset();

		placeManager.getCurrentTitle(placeManager.getHierarchyDepth() - 1,
			new SetPlaceTitleHandler() {

				@Override
				public void onSetPlaceTitle(String title) {
					TopBarPresenter.this.view.setTitle(title);
				}
			});
		int levels = placeManager.getHierarchyDepth() - 1;
		this.titlesRemaining = levels;
		this.breadcrumbs.clear();
		if (levels > 0) {
			for (int i = 0; i < levels; i++) {
				Breadcrumb crumb = new Breadcrumb(i);
				this.breadcrumbs.add(crumb);
				crumb.init();
			}
		} else {
			this.updateBreadcrumbs();
		}
	}

	private void updateBreadcrumbs() {
		if (this.titlesRemaining == 0) {
			this.view.setBreadcrumbs(this.breadcrumbs);
		}
	}
}
